//
//  AboutMeViewController.m
//  basic
//
//  Created by Jack on 2016/12/13.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "AboutMeViewController.h"
#import "SDPhotoBrowser.h"

@interface AboutMeViewController ()<UIWebViewDelegate,SDPhotoBrowserDelegate>{
    int imageIndex;
    NSString *objsLength;
    NSString *objsLengthURLs;
}

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, copy) NSString *imageUrl;
@property (strong,nonatomic) UIActivityIndicatorView *activityIndicator;

@end

static NSString * const BLOG = @"http://mp.weixin.qq.com/s/Rl8b_4cWIsh-XUK2XK4_QQ";

@implementation AboutMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.webView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.webView.backgroundColor=[UIColor whiteColor];
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:BLOG]];
    [self.webView loadRequest:request];
    self.webView.delegate=self;
    [self.view addSubview:self.webView];
    
//    NSString *path = [[NSBundle mainBundle] bundlePath];
////    NSString *path = [[NSBundle mainBundle] resourcePath];
//    NSURL *baseURL = [NSURL fileURLWithPath:path];
//    NSString *imageStr=[NSString stringWithContentsOfURL:[NSURL URLWithString:BLOG] encoding:NSUTF8StringEncoding error:nil];
//    [self.webView loadHTMLString:imageStr baseURL:baseURL];

    
    UIView *backlistViewContaint = [[UIView alloc]initWithFrame: CGRectMake(self.view.frame.size.width-65, self.view.frame.size.height-65-64, 40, 40)];
    [self.view addSubview:backlistViewContaint];
    backlistViewContaint.backgroundColor = UWORGB_COLOR(0, 126, 259);
    backlistViewContaint.layer.cornerRadius = 5;
    backlistViewContaint.layer.masksToBounds = YES;
    UIImageView *backlistView = [[UIImageView alloc]initWithImage:ImageWithName(@"icon_backlist")];
    backlistView.frame = CGRectMake(7.5, 7.5, 25, 25);
    backlistView.userInteractionEnabled = YES;
    UITapGestureRecognizer*tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backAction)];
    [backlistView addGestureRecognizer:tapGesture];
    backlistView.contentMode = UIViewContentModeScaleAspectFit;
    [backlistViewContaint addSubview:backlistView];
    
}

// 返回首页
-(void)backAction{
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:BLOG]];
    [self.webView loadRequest:request];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    //创建UIActivityIndicatorView背底半透明View
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    [view setTag:108];
    [view setBackgroundColor:[UIColor blackColor]];
    [view setAlpha:0.5];
    [self.view addSubview:view];
    
    _activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
    [_activityIndicator setCenter:view.center];
    [_activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    [view addSubview:_activityIndicator];
    
    [_activityIndicator startAnimating];
}

#pragma mark delegate method

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [_activityIndicator stopAnimating];
    UIView *view = (UIView*)[self.view viewWithTag:108];
    [view removeFromSuperview];
    
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    for(var i=0;i<objs.length;i++){\
    objs[i].onclick=function(){\
    document.location=\"myweb:imageClick:\"+this.src;\
    };\
    };\
    return objs.length;\
    };";
    
    
    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
    
    // 获取 img 的数量
    objsLength = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
    // 或方法 1 , 使用 jquery
//    objsLengthURLs = [_webView stringByEvaluatingJavaScriptFromString:@"var str=new Array();$('img').each(function(){str.push($(this).attr('src'));});str.join(',');"];
    // 或方法 2
    objsLengthURLs = [self.webView stringByEvaluatingJavaScriptFromString:@"var images= document.getElementsByTagName('img');var imageUrls = new Array();for(var i = 0; i < images.length; i++){var image = images[i];imageUrls.push(image.src);}imageUrls.join(',');"];
    
    
    // 替换本地背景图片 方法 1
    [self replaceLocalImage];
    // 方法2 网页有 js 报错，所以图片替换不了
//    NSString *imageSource = @"";
//    NSString *imageSource = @"https://www.baidu.com/img/bd_logo1.png";
//    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"replace.jpg" ofType:nil];
//    NSData *imageData=[NSData dataWithContentsOfFile:imagePath];//imagePath :沙盒图片路径
//    NSString *imageSource = [NSString stringWithFormat:@"data:image/png;base64,%@",[imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
//    NSString *strJs=[NSString stringWithFormat:@"setTimeout(\"document.getElementById('js_cover').src='%@';\",1000);",imageSource];
//    [webView stringByEvaluatingJavaScriptFromString:strJs];//注入js方法
}

// 替换本地背景图片
-(void)replaceLocalImage{
    //编码图片
    UIImage *selectedImage = [UIImage imageNamed:@"leading_4"];
    NSString *stringImage = [self htmlForJPGImage:selectedImage];
    //    document.getElementById("divId").style.backgroundImage="url(bg_1.gif)";
    NSString *strJs=[NSString stringWithFormat:@"setTimeout(\"document.getElementById('js_cover').src='%@';\",1000);",stringImage];
    [_webView stringByEvaluatingJavaScriptFromString:strJs];//注入js方法
}
//编码图片
- (NSString *)htmlForJPGImage:(UIImage *)image
{
    NSData *imageData = UIImageJPEGRepresentation(image,1.0);
    NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
    return imageSource;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [_activityIndicator stopAnimating];
    UIView *view = (UIView*)[self.view viewWithTag:108];
    [view removeFromSuperview];
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //将url转换为string
    NSString *requestString = [[request URL] absoluteString];
    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
        self.imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
        
//        for (int i=0; i<self.attachArray.count; i++) {
//            
//            if ([self.imageUrl containsString:self.attachArray[i][@"attachment"]]||[self.imageUrl containsString:self.attachArray[i][@"thumb"]]) {
//                imageIndex=i;
//                break;
//            }
//        }
        
        SDPhotoBrowser *browser=[[SDPhotoBrowser alloc]init];
        browser.sourceImagesContainerView = self.webView; // 原图的父控件
        browser.imageCount = objsLength.integerValue; // 图片总数
        browser.currentImageIndex = imageIndex;
        browser.delegate = self;
        browser.isNotAnimation=YES;
        [browser show];
        return NO;
    }
    else if([requestString hasPrefix:@"tel:"]){
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:requestString]];
        return NO;
    }
    return YES;
}

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    return nil;
}


- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    
    NSString *imageUrl=self.imageUrl;
    return [NSURL URLWithString:imageUrl];
    
}

@end
